package com.futvan.z.framework.util;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.http.HttpHost;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import com.futvan.z.framework.common.bean.ProxyIP;
import com.futvan.z.framework.common.bean.Result;
import com.futvan.z.framework.core.z;

/**
 * 公用接口工具类
 * @author zj
 *
 */
public class CommonServicesUtil {
	
	public static ProxyIP getProxyIP() {
		String url = "http://d.jghttp.golangapi.com/getip?num=1&type=1&pro=&city=0&yys=0&port=1&pack=17641&ts=0&ys=0&cs=0&lb=1&sb=0&pb=4&mr=1&regions=";
		String ip_txt = HttpUtil.doGet(url, null);
		String []ipportarray = ip_txt.split(":");
		String ip = ipportarray[0].trim();
		String port = ipportarray[1].trim();
		ProxyIP p = new ProxyIP();
		p.setIp(ip);
		p.setPort(new Integer(port));
		return p;
		
	}


	/**
	 * 获取代理IP列表
	 * @return
	 * @throws Exception 
	 */
	public static List<ProxyIP> getProxyIPList(int num){
		List<ProxyIP> iplist = new ArrayList<ProxyIP>();
		if(num>0) {
			String url = "http://d.jghttp.golangapi.com/getip?num="+num+"&type=1&pro=&city=0&yys=0&port=1&pack=10634&ts=0&ys=0&cs=0&lb=1&sb=0&pb=4&mr=2&regions=";
			String iplist_txt = HttpUtil.doGet(url, null);
			String [] iplist_array = iplist_txt.split("\\r?\\n");
			int t = 0;
			for (int i = 0; i < iplist_array.length; i++) {
				//才分IP与端口
				String ipport = iplist_array[i];
				String []ipportarray = ipport.split(":");
				//创建代理IP对象
				ProxyIP p = new ProxyIP();
				p.setIp(ipportarray[0]);
				p.setPort(new Integer(ipportarray[1]));
				iplist.add(p);
			}
		}
		return iplist;
	}

	/**
	 * 根据IP地区获取城市行政编号
	 * @param ip
	 * @return CityId
	 * 
	 * String cityId = CommonServicesUtil.getCityId("60.21.29.224");
	 * @throws Exception 
	 */
	public static String getCityId(String ip) throws Exception {
		String CityId = "";
		if(z.isNotNull(ip)) {
			String html = HttpUtil.doGet("http://ip.taobao.com/service/getIpInfo.php?ip="+ip, null);
			if(z.isNotNull(html)) {
				Map map = JsonUtil.getObject(html, Map.class);
				if(z.isNotNull(map)) {
					if(z.isNotNull(map.get("code")) && map.get("code") instanceof Integer) {
						Integer code = (Integer) map.get("code");
						if(code == 0) {
							if(z.isNotNull(map.get("data")) && map.get("data") instanceof Map) {
								Map data_map = (Map) map.get("data");
								if(z.isNotNull(data_map) && z.isNotNull(data_map.get("city_id"))) {
									CityId = String.valueOf(data_map.get("city_id"));
								}
							}
						}
					}
				}
			}
		}
		return CityId;
	}



}
